package com.example.demo.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;


@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
  //访问地址 http://localhost:8083/swagger-ui.html

  @Bean
  public Docket createRestApi() {
    // 请求头可选token
    ParameterBuilder tokenParam = new ParameterBuilder();
    List<Parameter> parameterList = new ArrayList<>();
    tokenParam.name("token").description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
    parameterList.add(tokenParam.build());
    // 创建 Docket 对象
    return new Docket(DocumentationType.SWAGGER_2) // 文档类型，使用 Swagger2


        .apiInfo(this.apiInfo()) // 设置 API 信息
        // 扫描 Controller 包路径，获得 API 接口
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.example.demo.cotroller"))
        .paths(PathSelectors.any())
        // 构建出 Docket 对象
        .build().globalOperationParameters(parameterList);
  }

  /**
   * 创建 API 信息
   */
  private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
        .title("测试接口文档示例")
        .description("我是一段描述")
        .version("1.0.0") // 版本号
        .build();
  }
}